import { Button } from '@renderer/components/ui/button'
import {
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerTitle
} from '@renderer/components/ui/drawer'
import { ScrollArea } from '@renderer/components/ui/scroll-area'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { createInsertSchema } from 'drizzle-zod'
import { pluginLocalTool } from '@shared/constant/schema'

import { PluginLocalTool } from '@shared/types/entity'
import { z } from 'zod'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@renderer/components/ui/form'
import { Input } from '@renderer/components/ui/input'
import { useEffect } from 'react'
import { useShallow } from 'zustand/react/shallow'
import usePluginLocalStore from '@renderer/store/plugin-local'
import usePluginLocalToolStore from '@renderer/store/plugin-local-tool'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@renderer/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@renderer/components/ui/tabs'
import { Textarea } from '@renderer/components/ui/textarea'
import InputToolSchema from '@renderer/components/ai/input-tool-schema'
import OutputToolSchema from '@renderer/components/ai/output-tool-schema'
import useInputToolSchemaStore from '@renderer/store/input-tool-schema'

const formSchema = createInsertSchema(pluginLocalTool)

const editByMark = async (data: PluginLocalTool) => {
  return await window.api.pluginLocalTool.editByMark(data)
}

const add = async (data: PluginLocalTool) => {
  return await window.api.pluginLocalTool.add(data)
}

export function DataDrawerFormTool() {
  console.log('DataDrawerFormTool')
  const { pluginList, initPluginList } = usePluginLocalStore(
    useShallow((state) => ({
      pluginList: state.data,
      initPluginList: state.initData
    }))
  )

  const {
    toolForm: { type, data },
    initToolData
  } = usePluginLocalToolStore(
    useShallow((state) => ({
      toolForm: state.form,
      initToolData: state.initData
    }))
  )

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: data
  })

  const { initSchema, getInputSchema } = useInputToolSchemaStore(
    useShallow((state) => ({
      initSchema: state.init,
      getInputSchema: state.getData
    }))
  )

  async function onSubmit(values: z.infer<typeof formSchema>) {
    console.log('提交pluginLocalTool-DataDrawerFormTool', type, values)
    if (type === 'add') {
      add({ ...values, inputSchema: getInputSchema() })
    } else {
      editByMark({ ...values, inputSchema: getInputSchema() })
    }
    initToolData()
  }

  useEffect(() => {
    form.reset(data)
    initSchema(data?.inputSchema || [])
    initPluginList()
  }, [data, type, form, initPluginList, initSchema])

  return (
    <DrawerContent className="!w-3/4 !max-w-none ">
      <div className="select-text p-4 h-full">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="h-full">
            <Tabs defaultValue="info" className="h-full flex flex-col">
              <DrawerTitle className="ml-1">
                {type === 'add' ? '新增' : '编辑'} 本地插件工具
              </DrawerTitle>
              <DrawerDescription>配置插件工具的基本信息和输入输出模式</DrawerDescription>
              <div className="flex items-center justify-between border-b py-2">
                <TabsList>
                  <TabsTrigger value="info">基本信息</TabsTrigger>
                  <TabsTrigger value="schema">输入/输出</TabsTrigger>
                </TabsList>
                <div className="flex space-x-2">
                  <DrawerClose asChild>
                    <Button type="submit">提交</Button>
                  </DrawerClose>
                  <DrawerClose asChild>
                    <Button variant="outline">取消</Button>
                  </DrawerClose>
                </div>
              </div>
              <div className="flex-1 overflow-hidden">
                <ScrollArea className="h-full">
                  <TabsContent value="info">
                    <FormField
                      control={form.control}
                      name="mark"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>唯一标识</FormLabel>
                          {type === 'add' ? (
                            <div className="flex items-center border rounded-md overflow-hidden">
                              <span className="bg-muted px-3 py-2 border-r text-gray-500 font-mono text-sm">
                                {data?.pluginMark + '.' || ''}
                              </span>
                              <FormControl className="flex-1 border-none">
                                <Input
                                  placeholder="Please input"
                                  {...field}
                                  className="border-none shadow-none focus-visible:ring-0"
                                />
                              </FormControl>
                            </div>
                          ) : (
                            <div className="bg-muted px-3 py-2 border rounded-md font-mono text-sm">
                              {data?.pluginMark + '.' + field.value}
                            </div>
                          )}
                          <FormDescription>格式：插件标识.工具标识</FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>名称</FormLabel>
                          <FormControl>
                            <Input placeholder="名称..." {...field} />
                          </FormControl>
                          <FormDescription>这是名称</FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="pluginMark"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>插件</FormLabel>
                          <FormControl>
                            <Select onValueChange={field.onChange} defaultValue={field.value}>
                              <SelectTrigger className="w-full">
                                <SelectValue placeholder="插件..." />
                              </SelectTrigger>
                              <SelectContent className="w-full">
                                {pluginList.map((item) => (
                                  <SelectItem key={item.mark} value={item.mark}>
                                    {item.name}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </FormControl>
                          <FormDescription>这是插件</FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="description"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>描述</FormLabel>
                          <FormControl>
                            <Textarea placeholder="描述..." {...field} />
                          </FormControl>
                          <FormDescription>这是描述</FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </TabsContent>
                  <TabsContent value="schema" className="space-y-6">
                    <InputToolSchema />

                    <FormField
                      control={form.control}
                      name="outputSchema"
                      render={({ field }) => (
                        <OutputToolSchema
                          initialSchema={field.value}
                          onSchemaChange={(schema) => field.onChange(schema)}
                        />
                      )}
                    />
                  </TabsContent>
                </ScrollArea>
              </div>
            </Tabs>
          </form>
        </Form>
      </div>
    </DrawerContent>
  )
}
